Create Connectomes at run time¶

In addition to loading connectomes from files and URLs, you ipyniivue can also create them dynamically. The notebook mirrors the JavaScript connectome web page.

In [1]:
from pathlib import Path

from ipyniivue import download_dataset

BASE_API_URL = "https://niivue.com/demos/images/"
DATA_FOLDER = Path("images")

# Download data for example
download_dataset(
    BASE_API_URL,
    DATA_FOLDER,
    files=[
        "mni152.nii.gz",
    ],
)
mni152.nii.gz already exists.
Dataset downloaded successfully to images.
In [2]:
import json

from IPython.display import display
from ipywidgets import Button, HBox, Layout, Textarea, VBox

from ipyniivue import NiiVue

# ---- constants ----
NV_HEIGHT = 380
TXT_HEIGHT = 380
TXT_WIDTH = 640

initial_connect = """{
    "name": "shearConnectome",
    "nodeColormap": "redyell",
    "nodeColormapNegative": "viridis",
    "legendLineThickness": 3,
    "nodeMinColor": 2,
    "nodeMaxColor": 5,
    "nodeScale": 3,
    "edgeColormap": "warm",
    "edgeColormapNegative": "winter",
    "edgeMin": 2,
    "edgeMax": 4,
    "edgeScale": 1,
    "nodes": {
        "names": ["Commissure", "Frontal", "Temporal", "Parietal"],
        "X": [0, -41, -54, -58],
        "Y": [0, 59, -6, -58],
        "Z": [0, 3, 16, 20],
        "Color": [3, 2, 4, 45],
        "Size": [2, 2, 3, 4]
    },
    "edges": [1, 4, -3, 4, 0, 1, 0, 6, 0, 0, 1, 0, 0, 0, 0, 1]
}"""

# ---- nv widget ----
nv = NiiVue(
    show_3d_crosshair=True,
    is_colorbar=True,
    multiplanar_force_render=True,
    height=NV_HEIGHT,
)
# Force ONLY the nv widget to have your fixed width/height
nv.layout = Layout(height=f"{NV_HEIGHT}px")
nv.set_clip_plane(-0.1, 0, 100)
nv.load_volumes([{"path": DATA_FOLDER / "mni152.nii.gz"}])
nv.volumes[0].colorbar_visible = False

# Example additional controls
text = Textarea(
    value=initial_connect,
    layout=Layout(width=f"{TXT_WIDTH}px", height=f"{TXT_HEIGHT}px"),
)
btn = Button(description="Custom")


def on_btn_clicked(b):
    """Load custom connectome."""
    json_bytes = json.dumps(json.loads(text.value.strip())).encode("utf-8")
    nv.load_from_array_buffer(json_bytes, "connect.jcon")


btn.on_click(on_btn_clicked)


@nv.on_image_loaded
def on_image_loaded(volume):
    """Load after volume is avaiable and nv attached to canvas."""
    btn.click()


# Display
box = VBox(
    [
        nv,
        HBox([text, btn]),  # any other widgets you want
    ],
    layout=Layout(
        overflow="visible"  # important: allow it to grow
    ),
)

display(box)